<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { FileAppApi } from '#/api/infra/fileapp';
import type { FileCategoriesApi } from '#/api/infra/filecategories';

import { nextTick, ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteFileApp,
  deleteFileAppList,
  getFileAppPage,
} from '#/api/infra/fileapp';
import { $t } from '#/locales';

import { fileappUseGridColumns } from '../data';
import Form from './fileapp-form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

// 当前文件分类
const fileCategories = ref<FileCategoriesApi.FileCategories>();

/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建应用文件分类授权 */
function handleCreate() {
  formModalApi.setData({ fileCategoriesId: fileCategories.value.id }).open();
}

/** 编辑应用文件分类授权 */
function handleEdit(row: FileAppApi.FileApp) {
  formModalApi.setData(row).open();
}

/** 删除应用文件分类授权 */
async function handleDelete(row: FileAppApi.FileApp) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteFileApp(row.id!);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除应用文件分类授权 */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteFileAppList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);

function handleRowCheckboxChange({
  records,
}: {
  records: FileAppApi.FileApp[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

const [Modal, modalApi] = useVbenModal({
  async onConfirm() {},

  async onOpenChange(isOpen: boolean) {
    if (!isOpen) return;

    const modalFileCategories =
      modalApi.getData<FileCategoriesApi.FileCategories>();
    if (!modalFileCategories) return;
    fileCategories.value = modalFileCategories;
    await nextTick(); // 等待 Grid 挂载
    await gridApi.reload();
  },
});

const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    id: 'FileApp-grid',
    columns: fileappUseGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          if (!fileCategories.value?.id) return { list: [], total: 0 };
          return await getFileAppPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              fileCategoriesId: fileCategories.value.id,
            },
            false,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<FileAppApi.FileApp>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Modal title="" class="w-2/3">
    <Page auto-content-height>
      <FormModal @success="handleRefresh" />
      <Grid table-title="应用文件分类授权列表">
        <template #toolbar-tools>
          <TableAction
            :actions="[
              {
                label: $t('ui.actionTitle.create', ['应用文件分类授权']),
                type: 'primary',
                icon: ACTION_ICON.ADD,
                auth: ['infra:file-app:create'],
                onClick: handleCreate,
              },
              {
                label: $t('ui.actionTitle.deleteBatch'),
                type: 'primary',
                danger: true,
                icon: ACTION_ICON.DELETE,
                disabled: isEmpty(checkedIds),
                auth: ['infra:file-app:delete'],
                onClick: handleDeleteBatch,
              },
            ]"
          />
        </template>
        <template #actions="{ row }">
          <TableAction
            :actions="[
              {
                label: $t('common.edit'),
                type: 'link',
                icon: ACTION_ICON.EDIT,
                auth: ['infra:file-app:update'],
                onClick: handleEdit.bind(null, row),
              },
              {
                label: $t('common.delete'),
                type: 'link',
                danger: true,
                icon: ACTION_ICON.DELETE,
                auth: ['infra:file-app:delete'],
                popConfirm: {
                  title: $t('ui.actionMessage.deleteConfirm', [row.id]),
                  confirm: handleDelete.bind(null, row),
                },
              },
            ]"
          />
        </template>
      </Grid>
    </Page>
  </Modal>
</template>
